package top.lingkang.mm.solon;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.noear.solon.Solon;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.BeanWrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lingkang.mm.MagicConfiguration;

import javax.sql.DataSource;
import java.util.Collection;

/**
 * @author lingkang
 * Created by 2024/3/11
 */
public class SolonMagicConfiguration extends MagicConfiguration {
    private static final Logger log = LoggerFactory.getLogger(SolonMagicConfiguration.class);

    public SolonMagicConfiguration() {
    }

    public SolonMagicConfiguration(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public SqlSessionFactory build() {
        SqlSessionFactory sessionFactory = super.build();
        Collection<Class<?>> mappers = getMapperRegistry().getMappers();
        if (!mappers.isEmpty()) {
            SqlSession session = sessionFactory.openSession();
            AppContext context = Solon.context();
            for (Class<?> clazz : mappers) {
                if (context.getBean(clazz) == null) {
                    // 注册bean
                    Object mapper = getMapper(clazz, session);
                    context.beanRegister(new BeanWrap(context, clazz, mapper), null, true);
                    log.debug("注册mapper到bean: {}", clazz.getName());
                }
            }
        }

        return sessionFactory;
    }
}
